#include "../../include/Configuration.hpp"

#include <dirent.h>
#include <string.h>
#include <unistd.h>

#include <fstream>
#include <iostream>
#include <sstream>
#include <ostream>

using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::istringstream;

int Configuration::getConf(const string &directory, vector<string> &storyFile, const string &confName)
{
    DIR *dir = opendir(directory.c_str());//打开目录
    if(nullptr == dir)
    {
        cout << directory << " open error\n" << endl;
        return -1;
    }

    struct dirent * d_ent = nullptr; //dirent 会存储每一个文件的属性
    char fullpath[128] = {0};
    char dot[3] = ".";//每个文件夹下都有.和..需要去掉
    char dotdot[6] = "..";

    while((d_ent = readdir(dir)) != nullptr)//一行一行读目录下的文件，将文件的属性存入d_ent结构体中
    {
        if((::strcmp(d_ent->d_name, dot) != 0 && (::strcmp(d_ent->d_name, dotdot) != 0)))
        {
            //d_type可以看到当前的东西的类型，DT_DIR代表当前到的都是目录
            if(d_ent->d_type == DT_DIR)
            {
                //d_name 中存放了子目录的名字
                string newDirectory = directory + string("/") + string(d_ent->d_name);
                if(directory[directory.length() - 1] == '/')
                {
                    newDirectory = directory + string(d_ent->d_name);
                }

                if(-1 == getConf(newDirectory, storyFile, confName))
                {
                    return -1;
                }
            }
            else
            {
                //如果不是子目录
                string absolutePath = directory + string("/") + string(d_ent->d_name);//构建绝对路劲
                if(directory[directory.length() - 1] == '/')
                {
                    absolutePath = directory + string(d_ent->d_name);
                }
                storyFile.push_back(absolutePath);
            }
        }
    }

    ofstream ofs(confName);
    for(auto &str : storyFile)
    {
        ofs << str << endl;
    }
    ofs.close();
    closedir(dir);
    return 0;
}
